<?php
/**
 * Created by PhpStorm.
 * User: 86151 - 姜伟
 * Date: 2023/8/7 9:53
 */

namespace Xinyu\Gen\Core\Libs;

use Illuminate\Support\Str;

class CommonClient extends BaseClient
{
    use SingletonUtil;

    // 获取name
    public function getName($name = '')
    {
        if (empty($name)) {
            return '';
        }
        $dbPrefix = env('DB_PREFIX');
        if (empty($dbPrefix)) {
            return $name;
        }
        $name = Str::snake($name);
        return Str::replaceFirst($dbPrefix, '', $name);
    }

    // 根据名称获取name,namespaceSuffix,savePath
    public function getNameParamsByName($name = '')
    {
        if (empty($name)) {
            return [];
        }
        $list = explode('/', $name);
        if (empty($list)) {
            return [];
        }
        $count = count($list);
        $namespaceSuffix = '';
        $savePath = '';
        $finalName = '';
        foreach ($list as $k => &$v) {
            $v = Str::studly($v);
            if ($k < $count - 1) {
                $namespaceSuffix .= '\\'.$v;
            } else {
                $finalName = last($list);
            }
            $savePath .= '/' . $v;
        }
        unset($v);
        return [
            'name' => $finalName,
            'namespace_suffix' => $namespaceSuffix,
            'save_path' => $savePath,
        ];
    }


    // 生成指定目录
    public function makeDir($savePath = '')
    {
        if (empty($savePath)) {
            return '';
        }
        $list = explode('/', $savePath);
        $last = Str::studly(last($list));
        unset($list[count($list) - 1]);
        $list = collect($list)
            ->map(function ($item, $index) {
                if ($index >= 2) {
                    $item = Str::studly($item);
                }
                return $item;
            })
            ->all();
        $dir = implode('/', $list);
        if (!is_dir($dir)) {
            if (!mkdir($dir, 0755, true) && !is_dir($dir)) {
                return $this->error("{$dir}文件创建失败");
            }
        }
        return $dir . '/' . $last;
    }
}


